import Taro from '@tarojs/taro'
import {BASE_URL, FACE, LX_LOGIN, OCR, SYSTEM_UPLOAD, TARO_ENV} from "../constants/api"
import fileUpload from './fileUpload'
import {http} from "./http";

/*
* 灵锡jsSdk
* */

class LXH5WxJsSdk {
  initCode
  requestCode
  isLogin = false
  appId = 'B730299428251008F'
  isLx = process.env.P_ENV === 'lx'

  jumpLogin = async () => {
    this.isLogin = true
    const {hostname, href} = window.location
    window.location.replace('http://' + hostname + LX_LOGIN + `?requestCode=${this.requestCode}&referer=${encodeURIComponent(href)}`)
  }

  getTokenFromCookies = () => {
    const arrCookies = document.cookie.replace(/\s+/g, '').split(";") // 分割
    // 遍历匹配
    for (let i = 0; i < arrCookies.length; i++) {
      const arr = arrCookies[i].split("=")
      if (arr[0] == 'token') {
        return true
      }
    }
    return false
  }

  lxPay = (orderId, callback)=>{
    ls.lsPay({
      orderId,
      version: '2'
    }, (res) => {
      if (res) {
        if (res.code === 9000) {
          Taro.showToast({ title:res.info, mask: true, icon: 'none', duration: 2000 })
          const timer = setTimeout(()=>{
            clearTimeout(timer)
            callback(false)
            Taro.redirectTo({url: '/main/order/order?status=0'})
          },2000)
        } else if (res.code === 200) {
          Taro.showToast({ title:res.info, mask: true, icon: 'none', duration: 2000 })
          const timer = setTimeout(()=>{
            clearTimeout(timer)
            callback(true)
          },2000)
        }
      }
    })
  }

  setShare = (title= '', icon= '', content= '')=> {
    ls.share({
      type: '3',
      title,
      content,
      image: icon,
      icon
    })
  }

  handlerError = (title)=> {
    Taro.showToast({
      title,
      icon: 'none'
    })
  }

  chooseImage = (callback, count, sizeType?, sourceType?) => {
    if (TARO_ENV === 'h5') {
      const inp = document.createElement('input');
      inp.setAttribute('type', 'file');
      inp.setAttribute('style', 'display: none;');
      inp['accept'] = '.jpg,.jpeg,.png,.gif'
      inp.multiple = count > 1
      document.body.appendChild(inp)
      inp.click()
      inp.onchange = (e: any) => {
        const files = e.target.files
        callback(e.target.files, files.length)
        document.body.removeChild(inp)
      }
    } else {
      Taro.chooseImage({
        count: count >= 10 ? 10 : count || 1,
        sizeType: sizeType || ['compressed'],
        sourceType: sourceType || ['album', 'camera'],
        success: (res) => {
          console.log(res)
          const tempFilePaths = res.tempFilePaths
          Taro.showToast({
            title: '正在上传...',
            icon: 'loading',
            mask: true,
            duration: 10000
          })
          callback(tempFilePaths, tempFilePaths.length)
        }
      })
    }
  }

  uploadOcr = (files, length, callback) => {
    this.handlerFile(OCR, files, length, callback, 'file', '识别中...')
  }

  uploadFace = (files, length, callback) => {
    this.handlerFile(FACE, files, length, callback, 'face')
  }

  uploadFile = (files, length, callback) => {
    this.handlerFile(SYSTEM_UPLOAD, files, length, callback, 'file')
  }

  handlerFile = async (api, files, length, callback, type, title = '上传中...') => {
    Taro.showToast({title, duration: 20000, mask: true, icon: 'loading'})
    for (let i = 0; i < length; i++) {
      const file = files[i]
      const formData = new FormData();
      formData.append(type, file);
      try {
        let data
        if (TARO_ENV === 'h5') {
          data = await fileUpload({url: api, data: formData})
        } else {
          data = await Taro.uploadFile({
            url: BASE_URL + api,
            filePath: file,
            name: 'file',
            formData,
            header: http.getHeader()
          })
          data = JSON.parse(data.data)
        }
        if (data.data) {
          if (type === 'face') {
            callback(data.data.domain + data.data.url)
          } else {
            callback(data.data)
          }
        }
        if (i === length -1){
          Taro.hideToast()
        }
        if (data.message && !data.data) {
          this.handlerError(data.message)
        }
      } catch (e) {
        this.handlerError(e.message)
      }
    }
  }

  // 打开微信小程序
  openWeChatApplet = (userName, path) => {
    ls.openWxMini({
      userName,
      path
    })
  }

  // 导航
  navigation = (lat = 0, lng = 0, address = '', name = '') => {
    if(this.isLx) {
      ls.lsMapNavi({lat, lng, name: address})
    } else {
      Taro.openLocation({
        latitude: lat,
        longitude: lng,
        address,
        name
      })
    }
  }

  scanCode = (callback) => {
    ls.qrCode((res) => {
      if (res.code === 200) {
        callback(res.data.scanString)
      } else {
        callback('')
      }
    })
  }

  jump = (url) => {
    ls.lsRouter({ url })
  }

  getRequestCode = (initCode, needLogin) => {
    //成功回调
    this.initCode = initCode
    ls.ready(() => {
      //自定义逻辑，如：
      //1.调用 JSSDK 里提供的交互方法
      //2.如需获取用户信息，需要在此处调用 ls.userAuth(Objectobject)方法获取requestCode。
      //  userAuth根据appid会自动判断是否需要登录、认证和授权。
      ls.userAuth({
        appId: this.appId, //从开放平台申请到的 appId
      }, async (res) => {
        if (res.code === 200) {
          this.requestCode = res.data.requestCode; //获取到requestcode
          if (needLogin && !this.isLogin && !this.getTokenFromCookies()) {
            await this.jumpLogin()
          }
          const user = Taro.getStorageSync('user') || ''
          if (!user || !user.pkey) {
            await this.jumpLogin()
          }
        } else if (res.code === 9005) {
          // 认证失败或登录失败
          alert('认证失败请稍后重试')
          // 如果在此处调用ls.close()关闭页面,需要延迟0.5秒执行，否则ls.close()会无效。
          setTimeout(() => {
            ls.close()
          }, 500)
        } else {
          // 其余情况
          // 如果在此处调用ls.close()关闭页面,需要延迟0.5秒执行，否则ls.close()会无效。
          setTimeout(() => {
            ls.close()
          }, 500)
        }
      })
    })

    //失败回调
    ls.error((res) => {
      //错误处理
      console.log('ls.error', res)
    })

    ls.config({
      debug: false, //开发时建议把调试模式开启
      appId: this.appId, //从开放平台申请到的 appId
      initCode //从业务方自己后台请求到 initCode
    })
  }
}

export const lxH5Wx = new LXH5WxJsSdk()
